﻿using MediatR;
using ProductionManagement.Application.Command.ProductionPlanCommand;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.ProductionPlanCommandHandler
{
    public class ProductionPlanDelCommandHandler : IRequestHandler<ProductionPlanDelCommand, int>
    {
        private readonly IProductionPlanRepository _productionPlanRep;
        private readonly IProductionProductRepository _productionProductRep;
        private readonly ISqlSugarClient db;
        public ProductionPlanDelCommandHandler(IProductionPlanRepository productionPlanRep, IProductionProductRepository productionProductRep, ISqlSugarClient db)
        {
            this._productionPlanRep = productionPlanRep;
            this._productionProductRep = productionProductRep;
            this.db = db;
        }

        public async Task<int> Handle(ProductionPlanDelCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _productionPlanRep.GetAll()).Where(x => request.ProductionPlansId.Contains(x.ProductionPlansId)).ToList();
                foreach (var material in list)
                {
                    material.IsDel = true;
                    material.DelName = request.DelName;
                    material.DelTime = DateTime.Now;
                    var item = (await _productionProductRep.GetAll()).Where(x => x.PPDocumentNumber == material.PPDocumentNumber).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel = true;
                        subpiece.DelName = request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _productionProductRep.UpdAsync(subpiece);
                    }
                    await _productionPlanRep.UpdAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
    }
}
